package com.zqweb.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.zqweb.common.utils.R;
import com.zqweb.gulimall.ware.feign.MemberFeignService;
import com.zqweb.gulimall.ware.vo.FareReceiveVo;
import com.zqweb.gulimall.ware.vo.MemberAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqweb.common.utils.PageUtils;
import com.zqweb.common.utils.Query;

import com.zqweb.gulimall.ware.dao.WareInfoDao;
import com.zqweb.gulimall.ware.entity.WareInfoEntity;
import com.zqweb.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        // 设置条件查询参数
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper) -> {
               wrapper.like("id",key).or().like("name",key).or()
                       .like("address",key).or().like("areacode",key);
            });
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareReceiveVo getFareByAddrId(Long addrId) {
        R r = memberFeignService.info(addrId);
        FareReceiveVo fareReceiveVo = new FareReceiveVo();
        if(r != null && r.getCode() == 0){
            System.out.println("远程的member服务调用成功...");
            MemberAddressVo memberAddressVo = r.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>(){});
            if(memberAddressVo != null){
                String detailAddress = memberAddressVo.getDetailAddress();
        // TODO项 根据收获地址和发货地址来确定最终的运费（这里是使用手机号的最后1位数值来表示运费值————模拟运费效果）
                String phone = memberAddressVo.getPhone();
                String lastBitNum = phone.substring(phone.length() - 1);
                // 将收获信息及fare信息封装成1个vo，便于前端更好地进行数据展示
                fareReceiveVo.setAddress(memberAddressVo);
                fareReceiveVo.setFare(new BigDecimal(lastBitNum));
            }
        }
        return fareReceiveVo;
    }

}